package hub

import (
	"context"
	"iot-base/common/redis"
	"sync/atomic"
)

var TaskManager = new(CaliManage)

func init() {
	redis.Del(redis.CaliInfoKey)
}

type CaliManage struct {
	key         string
	RunTaskType string //正在运行的任务类型
	isRun       uint32 //任务是否在运行
	runParams   map[string]interface{}
	params      map[string]interface{} //自定义参数
	taskId      string                 //正在运行的任务ID
	gasType     int                    //通气类型
	taskCurr    int                    //任务进度
	taskTotal   int                    //任务总数
	Ctx         context.Context
	cancelFunc  context.CancelFunc
}

func (c *CaliManage) TaskId() string {
	return c.taskId
}

func (c *CaliManage) SetTaskId(taskId string) {
	c.taskId = taskId
}

func (c *CaliManage) TaskCurr() int {
	return c.taskCurr
}

func (c *CaliManage) SetTaskCurr(taskCurr int) {
	c.taskCurr = taskCurr
}

func (c *CaliManage) TaskTotal() int {
	return c.taskTotal
}

func (c *CaliManage) SetTaskTotal(taskTotal int) {
	c.taskTotal = taskTotal
}

func (c *CaliManage) RestParams() {
	c.params = nil
	c.runParams = nil
	c.taskCurr = 0
	c.taskTotal = 0
}

// IsRun 是否有任务正在运行.
func (c *CaliManage) IsRun() bool {
	return atomic.LoadUint32(&c.isRun) == 1
}

// Lock 加锁.
func (c *CaliManage) Lock(key string) bool {
	// 获取lock
	isLock := atomic.CompareAndSwapUint32(&c.isRun, 0, 1)
	if isLock == true {
		// 更新校准状态
		redis.HSet(redis.CaliInfoKey, "is_cali", 1)
		c.Ctx, c.cancelFunc = context.WithCancel(context.Background())
		// 获取到锁之后才能设置锁的 key
		c.key = key
	}
	return isLock
}

// Unlock 解锁.
func (c *CaliManage) Unlock(key string) bool {
	// key 相同才能释放锁
	if key == c.key {
		isUnlock := atomic.CompareAndSwapUint32(&c.isRun, 1, 0)
		redis.Del(redis.CaliInfoKey)
		//redis.HSet(redis.CaliInfoKey, "is_cali", 0)
		return isUnlock
	}
	return false
}

// Stop 停止任务.
func (c *CaliManage) Stop() {
	if c.IsRun() {
		c.cancelFunc()
	}
}

func (c *CaliManage) GetGasType() int {
	return c.gasType
}

func (c *CaliManage) SetGasType(gasType int) {
	// 更新redis通气状态
	redis.HSet(redis.CaliInfoKey, "gas_type", gasType)
	c.gasType = gasType
}

func (c *CaliManage) SetTaskParams(params map[string]interface{}) {
	if v, ok := params["model_id"]; ok {
		redis.HSet(redis.CaliInfoKey, "model_id", v)
	}
	TaskManager.runParams = params
}

func (c *CaliManage) GetTaskParams() map[string]interface{} {
	resp := TaskManager.runParams
	if resp == nil {
		return map[string]interface{}{}
	}
	resp["curr"] = TaskManager.taskCurr
	resp["total"] = TaskManager.taskTotal
	resp["task_id"] = TaskManager.taskId
	return resp
}
